import React, { useState, useCallback, memo, useEffect } from 'react';
import ReactFlow, {
  Node,
  Edge,
  Controls,
  Background,
  useNodesState,
  useEdgesState,
  addEdge,
  Connection,
  ConnectionMode,
  NodeProps,
  NodeTypes,
  MarkerType,
  Handle,
  Position,
} from 'reactflow';
import { Modal, Form, Input, Select, Switch } from 'antd';
import { workflowTemplates, WorkflowTemplate, WorkflowNode, WorkflowNodeData } from '../../config/workflow-templates';
import 'reactflow/dist/style.css';

type NodeData = {
  label: string;
  config?: {
    fields: Array<{
      name: string;
      label: string;
      type: string;
      default?: any;
      options?: Array<{ label: string; value: string }>;
    }>;
  };
};

// 自定义节点组件
const CustomNode = memo(({ data, type }: NodeProps) => {
  const style = nodeStyles[type as keyof typeof nodeStyles] || nodeStyles.default;
  return (
    <div style={{ 
      padding: '10px 20px', 
      ...style, 
      borderRadius: '4px',
      minWidth: '120px',
      textAlign: 'center'
    }}>
      <Handle 
        type="target" 
        position={Position.Top} 
        style={{ background: '#555' }}
      />
      <div style={{ fontWeight: 'bold' }}>{data.label}</div>
      <Handle 
        type="source" 
        position={Position.Bottom} 
        style={{ background: '#555' }}
      />
    </div>
  );
});

// 节点样式配置
const nodeStyles = {
  development: { background: '#e6f7ff', border: '1px solid #91d5ff' },
  testing: { background: '#f6ffed', border: '1px solid #b7eb8f' },
  build: { background: '#fff7e6', border: '1px solid #ffd591' },
  deployment: { background: '#f9f0ff', border: '1px solid #d3adf7' },
  server: { background: '#e6fffb', border: '1px solid #87e8de' },
  cloud: { background: '#fcffe6', border: '1px solid #eaff8f' },
  monitoring: { background: '#fff1f0', border: '1px solid #ffa39e' },
  default: { background: '#ffffff', border: '1px solid #d9d9d9' },
};

// 边的默认样式
const defaultEdgeOptions = {
  type: 'smoothstep',
  animated: true,
  style: { stroke: '#91d5ff', strokeWidth: 2 },
  markerEnd: {
    type: MarkerType.ArrowClosed,
    color: '#91d5ff',
  },
};

// 节点类型定义
const nodeTypes: NodeTypes = {
  development: CustomNode,
  testing: CustomNode,
  build: CustomNode,
  deployment: CustomNode,
  server: CustomNode,
  cloud: CustomNode,
  monitoring: CustomNode,
};

const WorkflowDiagram: React.FC = () => {
  const [nodes, setNodes, onNodesChange] = useNodesState([]);
  const [edges, setEdges, onEdgesChange] = useEdgesState([]);
  const [selectedNode, setSelectedNode] = useState<Node | null>(null);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [selectedTemplate, setSelectedTemplate] = useState<string>(workflowTemplates[0].id);
  const [form] = Form.useForm();

  // 加载工作流模板
  const loadTemplate = useCallback((templateId: string) => {
    const template = workflowTemplates.find(t => t.id === templateId);
    if (template) {
      // 格式化节点
      const formattedNodes = template.nodes.map(node => ({
        id: node.id,
        type: node.type,
        position: node.position,
        data: {
          label: node.data.label,
          config: node.data.config,
        },
        style: {
          width: 'auto',
          minWidth: '120px',
        },
      }));
      
      // 格式化边
      const formattedEdges = template.edges.map(edge => ({
        ...edge,
        type: 'smoothstep',
        animated: true,
        style: { stroke: '#91d5ff', strokeWidth: 2 },
        markerEnd: {
          type: MarkerType.ArrowClosed,
          color: '#91d5ff',
        },
        labelStyle: { fill: '#666', fontSize: 12 },
        labelBgStyle: { fill: '#fff', fillOpacity: 0.7 },
      }));

      setNodes(formattedNodes);
      setEdges(formattedEdges);
    }
  }, [setNodes, setEdges]);

  // 初始化加载
  useEffect(() => {
    loadTemplate(workflowTemplates[0].id);
  }, [loadTemplate]);

  // 处理节点点击
  const onNodeClick = useCallback((event: React.MouseEvent, node: Node) => {
    setSelectedNode(node);
    setIsModalVisible(true);
    if (node.data?.config) {
      form.setFieldsValue(node.data.config);
    }
  }, [form]);

  // 处理连接
  const onConnect = useCallback((params: Connection) => {
    setEdges((eds) => addEdge({
      ...params,
      type: 'smoothstep',
      animated: true,
      style: { stroke: '#91d5ff', strokeWidth: 2 },
      markerEnd: {
        type: MarkerType.ArrowClosed,
        color: '#91d5ff',
      },
    }, eds));
  }, [setEdges]);

  // 渲染配置表单
  const renderConfigForm = () => {
    if (!selectedNode?.data?.config?.fields) return null;

    return (
      <Form form={form} layout="vertical">
        {selectedNode.data.config.fields.map((field: any) => {
          if (field.type === 'input') {
            return (
              <Form.Item
                key={field.name}
                name={field.name}
                label={field.label}
                initialValue={field.default}
              >
                <Input />
              </Form.Item>
            );
          }
          if (field.type === 'select') {
            return (
              <Form.Item
                key={field.name}
                name={field.name}
                label={field.label}
              >
                <Select options={field.options} />
              </Form.Item>
            );
          }
          if (field.type === 'switch') {
            return (
              <Form.Item
                key={field.name}
                name={field.name}
                label={field.label}
                valuePropName="checked"
              >
                <Switch />
              </Form.Item>
            );
          }
          return null;
        })}
      </Form>
    );
  };

  return (
    <div style={{ height: '80vh', width: '100%' }}>
      <Select
        style={{ width: '100%', marginBottom: 16 }}
        value={selectedTemplate}
        onChange={(value) => {
          setSelectedTemplate(value);
          loadTemplate(value);
        }}
        options={workflowTemplates.map(template => ({
          value: template.id,
          label: template.name,
        }))}
      />
      
      <div style={{ height: 'calc(80vh - 100px)', width: '100%', border: '1px solid #d9d9d9', borderRadius: '4px' }}>
        <ReactFlow
          nodes={nodes}
          edges={edges}
          onNodesChange={onNodesChange}
          onEdgesChange={onEdgesChange}
          onConnect={onConnect}
          onNodeClick={onNodeClick}
          nodeTypes={nodeTypes}
          defaultEdgeOptions={defaultEdgeOptions}
          connectionMode={ConnectionMode.Loose}
          fitView
          fitViewOptions={{ padding: 0.2 }}
          minZoom={0.5}
          maxZoom={2}
        >
          <Background />
          <Controls />
        </ReactFlow>
      </div>

      <Modal
        title={`配置 ${selectedNode?.data?.label}`}
        open={isModalVisible}
        onOk={() => {
          form.validateFields().then(values => {
            if (selectedNode) {
              setNodes(nds => 
                nds.map(node => 
                  node.id === selectedNode.id
                    ? { ...node, data: { ...node.data, config: values } }
                    : node
                )
              );
            }
            setIsModalVisible(false);
          });
        }}
        onCancel={() => setIsModalVisible(false)}
      >
        {renderConfigForm()}
      </Modal>
    </div>
  );
};

export default WorkflowDiagram; 